// 创建服务
var express = require('express');
const sql = require('mysql');
const crypto = require('crypto');
var router = express.Router();
var app = express()

//设置跨域访问
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Credentials', true);
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next()
});

// 连接数据库
let connection = sql.createConnection({
  host: 'localhost',
  user: 'root',
  password: 'root',
  port: '3306',
  database: 'web33'
});

connection.connect();
console.log("数据库连接成功")

//  登录
app.post('/', (req, res) => {
    var a = req.body
    console.log(a)
    let selectsql = "SELECT * FROM sys_user where user_name = '"+a.username+"' and password = '"+a.userpassword+"'";
     
    connection.query(selectsql, (err, result) => {
      if(err){
        console.log(err);
        console.log ("查询失败")
        return
      }
      // res.json({
      //   code:1,
      //   msg: result
      // })
      console.log(result);
      if(result.length == 0){
        let re = { msg:"登录失败", code:-1};
		    res.end(JSON.stringify(re));
      }else{
        let reData = {code:1, msg:"登录成功"};
		    res.end(JSON.stringify(reData));
      }
    })
  });
  module.exports = router;
  module.exports = app;
